import { reactive } from "vue";
import { MenuOption } from "naive-ui";
import { useRoute, useRouter } from "vue-router";

export function sideMenuEvent(menus: MenuOption[]) {
  // 当前路由
  const currentRoute = useRoute();
  const router = useRouter();
  // 获取当前打开的子菜单
  const matched = currentRoute.matched;

  const getOpenKeys =
    matched && matched.length ? matched.map((item) => item.name) : [];

  const state = reactive({
    openKeys: getOpenKeys,
  });

  const menuExpanded = (openKeys: string[]) => {
    if (!openKeys) return;
    const latestOpenKey = openKeys.find(
      (key) => state.openKeys.indexOf(key) === -1
    );
    const isExistChildren = findChildrenLen(latestOpenKey as string);
    state.openKeys = isExistChildren
      ? latestOpenKey
        ? [latestOpenKey]
        : []
      : openKeys;
  };
  //查找是否存在子路由
  const findChildrenLen = (key: string) => {
    if (!key) return false;
    const subRouteChildren: string[] = [];
    for (const { children, key } of menus) {
      if (children && children.length) {
        subRouteChildren.push(key as string);
      }
    }
    return subRouteChildren.includes(key);
  };

  // 点击菜单项路由跳转
  const handleUpdateMenu = async (key: string, item: MenuOption) => {
    await router.push({
      path: item.path as string,
    });
  };

  // const selectedKeys = ref<string>(currentRoute.name as string);

  // const getSelectedKeys = computed(() => {
  //   return unref(selectedKeys);
  // });
  //
  // watch(
  //   () => currentRoute.fullPath,
  //   () => {
  //     const matched = currentRoute.matched;
  //     state.openKeys = matched.map((item) => item.name);
  //     const activeMenu: string =
  //       (currentRoute.meta?.activeMenu as string) || "";
  //     selectedKeys.value = activeMenu
  //       ? (activeMenu as string)
  //       : (currentRoute.name as string);
  //   }
  // );

  return {
    handleUpdateMenu,
    menuExpanded,
  };
}
